<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property integer $id
 * @property integer $parent_id
 * @property string $name
 * @property string $url
 * @property integer $language_id
 * @property string $meta_keyword
 * @property string $meta_description
 * @property string $content
 * @property integer $status
 * @property integer $rank
 */
class Category extends MyARContent
{

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Category the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{category}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
        return array(
            array('parent_id, language_id, status, rank', 'numerical', 'integerOnly' => true),
            array('name', 'length', 'max' => 155),
            array('meta_keyword, meta_description', 'length', 'max' => 255),
            array('url, content, icon, symbol', 'safe'),
            // The following rule is used by search().
// Please remove those attributes that should not be searched.
            array('id, parent_id, name, url, language_id, meta_keyword, meta_description, content, status, rank', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
        $relations = parent::relations();
        $relations['posts'] = array(self::HAS_MANY, 'Post', 'category_id',
            'condition' => 'status=1', 'limit' => 4, 'order' => 'id DESC');
        $relations['postHl'] = array(self::HAS_ONE, 'Post', 'category_id',
            'condition' => 'status=2', 'order' => 'id DESC');
        return $relations;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        $array = array(
            'id' => 'ID',
            'parent_id' => 'Parent',
            'name' => 'Name',
            'url' => 'Url',
            'language_id' => 'Language',
            'meta_keyword' => 'Meta Keyword',
            'meta_description' => 'Meta Description',
            'content' => 'Content',
            'status' => 'Status',
            'rank' => 'Rank',
            'symbol' => 'Loại tin',
        );
        foreach ($array as $key => $val)
        {
            $array[$key] = Yii::t('category', $val);
        }
        return $array;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
// Warning: Please modify the following code to remove attributes that
// should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('parent_id', $this->parent_id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('url', $this->url, true);
        $criteria->compare('language_id', $this->language_id);
        $criteria->compare('meta_keyword', $this->meta_keyword, true);
        $criteria->compare('meta_description', $this->meta_description, true);
        $criteria->compare('content', $this->content, true);
        $criteria->compare('status', $this->status);
        $criteria->compare('rank', $this->rank);
        $criteria->compare('symbol', $this->symbol);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Lấy các phần tử Danh mục thành một mảng, sử dụng cho form bài viết khi chọn
     * danh mục hoặc form Danh mục khi chọn danh mục cha
     * 
     * @param array $blacklist Mảng các id của những category không muốn hiển thị trong ds này
     * @return array Một mảng các category với key là id, value là name
     */
    public static function getPublicArrayMenu($blacklist = array())
    {
        $root = array(
            0 => Yii::t('category', 'Select category')
        );
        $array = $root + self::getSubCateMenu(0, $blacklist);
        return $array;
    }

    static function getSubCateMenu($parent_id, $blacklist = array(), $separated = "|-- ")
    {
        $cri = new CDbCriteria;
        $cri->condition = "status!=0 AND parent_id=:parent and language_id = :l";
        $cri->params = array(
            ':parent' => $parent_id,
            ':l' => Yii::app()->controller->lang_id,
        );
        $children = self::model()->findAll($cri);

        /* Lay danh sach cac thu muc con */
        $array = array();
        foreach ($children as $child)
        {
            if (in_array($child->id, $blacklist))
            {
                continue;
            }

            $array[$child->id] = array(
                'text' => $separated . $child->name,
                'name' => $child->name,
            );
            $childArray = self::getSubCateMenu($child->id, $blacklist, $separated . "|-- ");
            if (!empty($childArray))
            {
                $array = $array + $childArray;
            }
        }
        return $array;
    }

    /**
     * Lấy các phần tử Danh mục thành một mảng, sử dụng cho form bài viết khi chọn
     * danh mục hoặc form Danh mục khi chọn danh mục cha
     * 
     * @param array $blacklist Mảng các id của những category không muốn hiển thị trong ds này
     * @return array Một mảng các category với key là id, value là name
     */
    public static function getPublicArray($blacklist = array())
    {
        $root = array(
            0 => Yii::t('category', 'Select category')
        );
        $array = $root + self::getSubCate(0, $blacklist);
        return $array;
    }

    static function getSubCate($parent_id, $blacklist = array(), $separated = "|-- ")
    {
        $cri = new CDbCriteria;
        $cri->condition = "status!=0 AND parent_id=:parent and language_id = :l";
        $cri->params = array(
            ':parent' => $parent_id,
            ':l' => Yii::app()->controller->lang_id,
        );
        $children = self::model()->findAll($cri);

        /* Lay danh sach cac thu muc con */
        $array = array();
        foreach ($children as $child)
        {
            if (in_array($child->id, $blacklist))
            {
                continue;
            }
            $array[$child->id] = $separated . $child->name;
            $childArray = self::getSubCate($child->id, $blacklist, $separated . "|-- ");
            if (!empty($childArray))
            {
                $array = $array + $childArray;
            }
        }
        return $array;
    }

    public function getPublicUrl($absolute = false)
    {
        if ($absolute == FALSE)
        {
            return Yii::app()->createUrl("post/index", array(
                    'url' => $this->url,
            ));
        }
        else
        {
            return Yii::app()->createAbsoluteUrl("post/index", array(
                    'url' => $this->url,
            ));
        }
    }

    public function getCateUrl()
    {
        return Yii::app()->createUrl("post/index", array(
                'url' => $this->url,
        ));
    }

    public static function getCateName($idcate)
    {
        $cate = self::model()->findByPk($idcate);
        return $cate->name;
    }

    public static function getCateAll($parent_id)
    {
        $cri = new CDbCriteria;
        $cri->condition = "parent_id=:parent and status>0";
        $cri->params = array(
            ':parent' => $parent_id,
        );
        $cri->order = 'rank ASC';
        return self::model()->findAll($cri);
    }

    public static function getAllCategory($parent_id, $bool = TRUE)
    {
        if ($bool == FALSE)
        {
            $cri = new CDbCriteria;
            $cri->condition = "parent_id=:parent and status = :s";
            $cri->params = array(
                ':parent' => $parent_id,
                ':s' => Category::STATUS_HIGHLIGHT,
            );
        }
        else
        {
            $cri = new CDbCriteria;
            $cri->condition = "parent_id=:parent and status = :s";
            $cri->params = array(
                ':parent' => $parent_id,
                ':s' => Category::STATUS_PUBLIC,
            );
        }
        $cri->order = 'rank ASC';
        $children = Category::model()->findAll($cri);
        /* Lay danh sach cac thu muc con */
        $array = array();

        foreach ($children as $child)
        {
            //tim thang con
            $childArray = self::getAllCategory($child->id);
            if (!empty($childArray))
            {
                foreach ($childArray as $cat_id)
                {
                    $array[] = $cat_id->id;
                }
            }
            $array[] = $child->id;
        }
        $arr = array_unique($array);

        return $arr;
    }

    public function getHighlightPost()
    {
        $post = Post::model()->find("status=:s AND category_id=:c", array(
            ':s' => Post::STATUS_HIGHLIGHT,
            ':c' => $this->id));
        if (!$post)
        {
            $post = Post::model()->find("status=:s AND category_id=:c", array(
                ':s' => Post::STATUS_PUBLIC,
                ':c' => $this->id));
        }
        return $post;
    }

}